package com.thti.mecool.client.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import com.thti.mecool.client.adapter.TaskOptionAdapter;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.base.ImageUpload;
import com.thti.mecool.client.model.biz.TaskBizImpl;
import com.thti.mecool.client.model.biz.TaskManageBizImpl;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.model.po.TaskStep;
import com.thti.mecool.client.util.ImageUtil;
import com.thti.mecool.client.util.NetTool;
import com.thti.mecool.client.util.NetTool.NetProgress;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.IsOKListener;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

import java.util.*;

public class TaskExecute extends BaseActivity {
	private Intent i;
	private TaskStepBizImpl taskStepBizImpl;
	private ListView StepList;

	private SharedPreferences load;
	private TaskOptionAdapter TaskStepAdapter;
	private String[] StepNameArr = null,StepIds=null,parentStepIds=null;
	private String taskId = null;
	private TaskBizImpl taskBizImpl;
	private int[] ActionIds = null;
	private String PlanId, ProjectId,storeName,storeCode;
	private ProgressDialogWidget pd;
	private int curItem;
	private HashMap<String, Integer> finishStat;
	private TaskManage taskManage;
	private String taskName,storeAddress;
	private ImageUpload imageUpload;
	HashMap<String,Bitmap> images=new HashMap<String, Bitmap>();
	ArrayList<HashMap<String, String>> tasks=new ArrayList<HashMap<String,String>>();
	HashMap<String, String> task=new HashMap<String, String>();
	String parentStepId;
	private Runnable r=new Runnable() {
		@Override
		public void run() {
			if(getDataFlag(HandlerConstant.UploadImgCommand)){
				imageUpload.uploadImage(1,tasks);
				taskBizImpl.uploadTask("1",tasks);
				removeDataFlag(HandlerConstant.UploadImgCommand);
				pd.setProgress(100);
				h.post(r);
			}else if(getDataFlag(HandlerConstant.UploadCurCommand)){
				if(pd.isShowing())
					pd.dismiss("上传成功！");
				taskBizImpl.uploadTask("2",tasks);
				taskBizImpl.taskFinish("1",PlanId, taskId, ProjectId, String.valueOf(getCurrentUser().getId()));
				Intent i=new Intent(TaskExecute.this,TaskActivity.class);
				i.putExtra("echo", true);
				startActivity(i);
				removeDataFlag(HandlerConstant.UploadCurCommand);
				finish();
			}	else{
					h.postDelayed(r, 1000);
				}
		}
	};
	
	private Handler h;

	private HashMap<String,Bitmap> findThumbnails(){
		HashMap<String, Bitmap> images=new HashMap<String, Bitmap>();
		TaskManageBizImpl bizImpl=new TaskManageBizImpl(this);
		List<TaskManage> list=bizImpl.findByImages(tasks);
		System.out.println("list    Size    :"+list.size());
		for(TaskManage tm:list){
			byte[] buf=tm.getImages();
			if(buf!=null)
			images.put(tm.getStepId(), ImageUtil.getThumbnail(buf,60,true));
			else
				images.put(tm.getStepId(), null);
		}
		return images;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_task_option_list);
		Cache.add(this);
		StepList = (ListView) findViewById(R.id.mecool_task_option_list);
		load = getSharedPreferences("LocationService", 0);
		i = getIntent();
		h=new Handler();
		finishStat=new HashMap<String, Integer>();
		storeName=i.getStringExtra("storeName");
		storeCode=i.getStringExtra("storeCode");
		PlanId = i.getStringExtra("planId");
		ProjectId = i.getStringExtra("projectId");
		taskName=i.getStringExtra("taskName");
		taskId=i.getStringExtra("taskId");
		taskStepBizImpl = new TaskStepBizImpl(this);
		task.put("planId", PlanId);
		task.put("taskId", taskId);
		tasks.add(task);
		
		if (PlanId != null & ProjectId != null) {
			List<TaskStep> taskSteps = taskStepBizImpl.findByjob(PlanId,
					ProjectId, taskId,0);
			StepNameArr = new String[taskSteps.size()];
			ActionIds = new int[taskSteps.size()];
			StepIds=new String[taskSteps.size()];
			parentStepIds=new String[taskSteps.size()];
			storeAddress=taskSteps.get(0).getStoreAddress();
			for (int i = 0; i < taskSteps.size(); i++) {
				parentStepIds[i]=taskSteps.get(i).getParentId();
				StepNameArr[i] = taskSteps.get(i).getName();
				ActionIds[i] = taskSteps.get(i).getActionId();
				StepIds[i]=taskSteps.get(i).getStepId();
				if(taskSteps.get(i).getActionId()!=9)
				finishStat.put(taskSteps.get(i).getStepId(), 0);
			}
		}

		if (StepNameArr != null) {
			System.out.println(Arrays.toString(StepIds));
			images.putAll(findThumbnails());
			TaskStepAdapter = new TaskOptionAdapter(this, StepNameArr,ActionIds,finishStat,StepIds,images);
			StepList.setAdapter(TaskStepAdapter);
		}

		TaskStepAdapter.setDataId(ProjectId, PlanId, taskId);
		
		OnItemClickListener StepClickListener = new OnItemClickListener() {
			private void startAction(int arg2,String parentStepId){
				i.putExtra("parentStepId", parentStepId);
				i.setClass(TaskExecute.this, TaskStepActionActivity.class);
				i.putExtra("curStepItems", arg2);
				i.putExtra("text_name", StepNameArr[arg2]);
				i.putExtra("planId", PlanId);
				i.putExtra("projectId", ProjectId);
				i.putExtra("taskName", taskName);
				if(!StringUtil.isBlank(storeAddress)){
				   i.putExtra("storeAddress", storeAddress);
				}else {
				   i.putExtra("storeAddress", "");
				}
				if (taskId != null) {
					i.putExtra("parentId", StepIds[arg2]);
				}
				startActivityForResult(i,1);
			}
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				taskManage=new TaskManage();
				taskManage.setPlanId(PlanId);
				taskManage.setProjectId(ProjectId);
				taskManage.setTaskId(taskId);
				taskManage.setStepId(StepIds[arg2]);
				taskManage.setIsUpload(0);
				parentStepId=StepIds[arg2];
				curItem=arg2;
                i.putExtra("taskId", taskId);
				switch (ActionIds[arg2]) {
				case 1:
					i.setClass(TaskExecute.this, CameraActivity.class);
					i.putExtra("planId", PlanId);
					i.putExtra("projectId", ProjectId);
//					i.putExtra("taskId", taskId);
					i.putExtra("StepId", StepIds[arg2]);
					if (taskId != null) {
						i.putExtra("parentId", StepIds[arg2]);
					}
					startActivity(i);
					break;
				case 2:
					AlterDialogWidget ad = new AlterDialogWidget(
							TaskExecute.this);
					ad.setEditTextDialog();
					ad.setReturnView(arg1.findViewWithTag("tv2"));
					ad.setIsOKListener(isOKListener);
					ad.show();
					taskManage.setIsType(2);
					break;
				case 3:
					AlterDialogWidget ad2 = new AlterDialogWidget(
							TaskExecute.this);
					ad2.setEditTextDialog();
					ad2.setIsNumEt(true);
					ad2.setReturnView(arg1.findViewWithTag("tv2"));
					ad2.setIsOKListener(isOKListener);
					ad2.show();
					taskManage.setIsType(2);
					break;
				// 单选框
				case 4:
					android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case -1:
								clearStep(parentStepId);
								List<Map<String,Object[]>> list=new ArrayList<Map<String,Object[]>>();
								Map<String,Object[]> arg=new HashMap<String,Object[]>();
								//isFinsh=? where planId=? and projectId=?  and stepId=? and taskId=?";
								arg.put(HandlerConstant.PLAN_UPDATE_SQL, new String[]{"0",PlanId,ProjectId,StepIds[curItem],taskId});
								arg.put(HandlerConstant.TASK_STEP_UPDATE_DATA_SQL, new String[]{null,PlanId,ProjectId,StepIds[curItem],taskId});
								list.add(arg);
								taskStepBizImpl.updateStep(list);
								startAction(curItem, parentStepId);
								break;
							default:
								break;
							}
						}
					};
					if(taskStepBizImpl.findStepFinish(PlanId, taskId, ProjectId,StepIds[curItem])){
						new AlertDialog.Builder(TaskExecute.this).setTitle("提示")
						.setMessage("已完成的步骤将被清空，确认要执行吗？")
						.setNegativeButton("取消", dialogClickListener)
						.setPositiveButton("确认", dialogClickListener).create()
						.show();
					}else{
						startAction(arg2, parentStepId);
					}
					break;
				case 5:

					clearStep(parentStepId);

					List<Map<String,Object[]>> list=new ArrayList<Map<String,Object[]>>();
					Map<String,Object[]> arg=new HashMap<String,Object[]>();
					arg.put(HandlerConstant.PLAN_UPDATE_SQL, new String[]{"0",PlanId,ProjectId,StepIds[curItem],taskId});
					arg.put(HandlerConstant.TASK_STEP_UPDATE_DATA_SQL, new String[]{null,PlanId,ProjectId,StepIds[curItem],taskId});
					list.add(arg);
					taskStepBizImpl.updateStep(list);
					
					i.setClass(TaskExecute.this, MultipleChoice.class);
					i.putExtra("planId", PlanId);
					i.putExtra("projectId", ProjectId);
					i.putExtra("parentId", StepIds[arg2]);
					i.putExtra("text_name", StepNameArr[arg2]);
					i.putExtra("parentStepId", parentStepId);
					startActivity(i);
					break;
				case 6:
					i.setClass(TaskExecute.this,TaskStepScoreActivity.class);
					i.putExtra("planId", PlanId);
					i.putExtra("projectId", ProjectId);
					i.putExtra("parentId", StepIds[arg2]);
					i.putExtra("text_name", StepNameArr[arg2]);
					startActivity(i);
					break;
				case 7:
					i.setClass(TaskExecute.this,ChoiceFileActivity.class);
					i.putExtra("planId", PlanId);
					i.putExtra("projectId", ProjectId);
//					i.putExtra("taskId", taskId);
					i.putExtra("stepId", StepIds[arg2]);
					startActivity(i);
					break;
				case 9:
					List<TaskStep> taskSteps = taskStepBizImpl.findFinishSteps(ProjectId,taskId);
						if(taskSteps.size()==finishStat.size()){
					imageUpload=new ImageUpload(TaskExecute.this);
					pd=new ProgressDialogWidget(TaskExecute.this,false);
					pd.upProgress();
					Thread t=new Thread(){
						@Override
						public void run() {
							NetTool.setNetProgress(netProgress);
							int isUpload=taskBizImpl.findUpload(PlanId, taskId);
							if(isUpload==1){
								imageUpload.uploadImage(1, tasks);
								pd.setProgress(100);
							}
							else
								imageUpload.uploadImage(0,tasks);
						};
					};
					t.start();
					pd.show();
					Util.sendToast(TaskExecute.this, "正在上传！");
					h.post(r);}
					else{
						Util.sendToast(TaskExecute.this, "尚未完成该任务！");
					}
					break;
				}
			}
		};
		StepList.setOnItemClickListener(StepClickListener);
		initToolbar();
	}
	private IsOKListener isOKListener = new IsOKListener() {
		@Override
		public void isOk(boolean isPutOk, String content) {
			if (isPutOk) {
				complete(content);
			}
		}
	};
	
	NetProgress netProgress=new NetProgress() {
		
		@Override
		public void progress(int progress) {
			System.out.println("测试上传进度  ：    "+progress);
			if(progress<100)
			pd.setProgress(progress);
		}
	};
	private void clearStep(String parentId){
		taskStepBizImpl.clearStep(PlanId, taskId, parentId, ProjectId);
	}
	private void complete(String content) {
		taskManage.setData(content);
		taskManage.setLatitude(load.getString("Latitude", null));
		taskManage.setLongitude(load.getString("Longitude", null));
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
		List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
		Map<String, Object[]> map = new HashMap<String, Object[]>();
		String[] ids = new String[] { "1", PlanId, ProjectId, StepIds[curItem], taskId };
		map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
		list.add(map);
		taskStepBizImpl.updateStep(list);
		taskStepBizImpl.updateData(taskManage);
		refresh();
	}
@Override
protected void onResume() {
	super.onResume();
	refresh();
}
public void refresh(){

	taskBizImpl=new TaskBizImpl(this);
	images.clear();
	images.putAll(findThumbnails());
	List<TaskStep> taskSteps = taskStepBizImpl.findFinishSteps(ProjectId,taskId);
	if (taskSteps.size() > 0) {
		if(taskSteps.size()==finishStat.size()){
			
//			android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					Intent i=new Intent(TaskExecute.this,TaskActivity.class);
//					switch (which) {
//					case -1:
						taskBizImpl.taskFinish("1",PlanId, taskId, ProjectId, String.valueOf(getCurrentUser().getId()));
//						i.putExtra("echo", true);
//						startActivity(i);
//						finish();
//						break;
//					default:
//						dialog.dismiss();
//						break;
//					}
//				}
//			};
//				new AlertDialog.Builder(TaskExecute.this).setTitle("提示")
//				.setMessage("已完成当前任务！")
//				.setNegativeButton("暂置为待办任务", dialogClickListener)
//				.setPositiveButton("存为已完成任务", dialogClickListener).create()
//				.show();
		}

		for(Iterator<String> it=finishStat.keySet().iterator();it.hasNext();){
			String StepId=it.next();
			finishStat.put(StepId, 0);
		}
		
		for (TaskStep ts : taskSteps) {
			finishStat.put(ts.getStepId(), 1);
		}
	}else{
		for(Iterator<String> it=finishStat.keySet().iterator();it.hasNext();){
			String StepId=it.next();
			finishStat.put(StepId, 0);
		}
	}
	TaskStepAdapter.notifyDataSetChanged();
	
}
	public void initToolbar() {
		Toolbar toolbar = new Toolbar(this);
		toolbar.setToolbarCentreText(taskName);
		Toolbar.hideRightButton();
		Toolbar.left_btn.setOnClickListener(buttonListener);
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
		Toolbar.right_btn.setVisibility(0);
		Toolbar.right_btn.setImageResource(R.drawable.mecool_add_work_memo_add);
		Toolbar.right_btn.setOnClickListener(buttonListener);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==4){
			Intent i=new Intent(this,TaskActivity.class);
			i.putExtra("echo", true);
			startActivity(i);
finish();
		}
		return false;
	}
	private OnClickListener buttonListener = new ImageButton.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_rightbtn:
				Intent in=new Intent(TaskExecute.this,AddWorkMemoActivity.class);
				in.putExtra("TaskExcuteFlag", true);
				in.putExtra("storeName", storeName);
				in.putExtra("storeCode", storeCode);
				startActivity(in);
//				in.putExtra("WorkMemoExcuteId", 10);
//				in.putExtra("workmemoshop", shop.getText().toString());
//				in.putExtra("workmemocontent", content.getText().toString());
//				in.putExtra("curItemCode", curItemCode);
//				in.putExtra("curCommId", curCommId);
				break;

			default:
				Intent i=new Intent(TaskExecute.this,TaskActivity.class);
				i.putExtra("echo", true);
				startActivity(i);
				finish();
				break;
			}

		}
	};
}
